package com.yaorange.jk.service.impl;

import com.yaorange.jk.dao.BaseDao;
import com.yaorange.jk.entity.Invoice;
import com.yaorange.jk.entity.PackingList;
import com.yaorange.jk.service.InvoiceService;
import com.yaorange.jk.service.PackingListService;
import com.yaorange.jk.utils.Pagination;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;


@Transactional
@Service
public class InvoiceServiceImpl implements InvoiceService {
    @Autowired
    private BaseDao<Invoice,String> invoiceDao;

    @Autowired
    private PackingListService packingListService;
    @Override
    public Pagination findPage(Pagination page) {
        return invoiceDao.pageByHql("from Invoice",page.getPageNo(),page.getPageSize());
    }

    @Override
    public Pagination findSubmitInvoicePage(Pagination page) {
        return invoiceDao.pageByHql("from Invoice i where i.state = 1",page.getPageNo(),page.getPageSize());
    }

    @Override
    public List<Invoice> findAll() {
        return invoiceDao.getListByHQL("from Invoice");
    }

    @Override
    public void save(Invoice model) {
        invoiceDao.save(model);
        //发票新增时，因为装箱单的发票号，前期是没有值的，
        // 所以当发票生成时，发票号就存在值了，就要更新装箱单的发票号
        PackingList pl = packingListService.findById(model.getId());
        pl.setInvoiceNo(model.getScNo());
        Date d = null;
        try {
            d = new SimpleDateFormat("yyyy-MM-dd").parse(model.getBlNo());
        } catch (ParseException e) {
            e.printStackTrace();
        }
        pl.setInvoiceDate(d);
        packingListService.update(pl);
    }



    @Override
    public void updateStateById(int status, String id) {
        String[] ids = id.split(", ");
        double d = (double)status;
        for (String i: ids){
            invoiceDao.executeHql("update Invoice i set i.state = ? where i.id = ?",d,i);
        }
    }

    @Override
    public void deleteById(String id) {
    invoiceDao.deleteById(Invoice.class,id);
    }

    @Override
    public void update(Invoice model) {
    invoiceDao.update(model);
    }

    @Override
    public Invoice findById(String id) {
    return invoiceDao.get(Invoice.class,id);
    }
}
